package de.yvert.jingle.help;

public class Half
{

public static float shortBitsToHalf(int bits)
{
	int s = (bits >> 15) & 1;
	int e = (bits >> 10) & 0x1f;
	int m = bits & 0x3ff;
	
	if ((e > 0) && (e < 31))
	{
//		(-1)^s * 2^(e - 15) * (1 + m / 2^10)
		e = e-15+127;
		return Float.intBitsToFloat((s << 31) | (e << 23) | (m << 13));
	}
	else if (e == 0)
	{
		if (m == 0)
			return Float.intBitsToFloat(s << 31);
		else
			return Float.intBitsToFloat((s << 31) | (m << 13));
	}
	else
	{
		if (m == 0)
			return s == 1 ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
		else
			return Float.NaN;
	}
}

// float = 1+8+23
// half  = 1+5+10
public static short halfToShortBits(float value)
{
	int bits = Float.floatToIntBits(value);
	int s = (bits >> 31) & 1;
	int e = (bits >> 23) & 0xff;
	int m = bits & 0x7fffff;
	if (e == 0) return (short) (s << 15);
	e = e-127+15;
	if (e < 0) return 0; //throw new IllegalArgumentException();
	if (e > 0x1f) throw new IllegalArgumentException();
	m = m >> 13;
	if (m > 0x3ff) throw new IllegalArgumentException();
	return (short) ((s << 15) | (e << 10) | m);
}

}
